import 'dart:collection';

import 'package:cloud_phone_manager/provider/AdbCurrentChangeProvider.dart';
import 'package:cloud_phone_manager/provider/AdbDevicesProvider.dart';
import 'package:cloud_phone_manager/utils/CmdUtils.dart';
import 'package:cloud_phone_manager/utils/ConnectUtils.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import '../data/PhoneFile.dart';

/// 设备列表
class FileManagerView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _FileManagerView();
}

class _FileManagerView extends State<FileManagerView> {
  List<PhoneFile> _list = [];
  AdbCurrentChangeProvider? provider;
  List<PhoneFile> _listRight = [];
  bool _isInit = false;
  bool _mounted = false;

  @override
  void initState() {
    super.initState();
    _mounted = true;
    if (!_isInit) {
      _isInit = true;
      initList();
    }
  }

  @override
  void dispose() {
    _mounted = false;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (provider == null) {
      provider = Provider.of<AdbCurrentChangeProvider>(context);
      debugPrint("注册监听");
      provider?.addListener(() {
        debugPrint("开始刷新界面");
        initList();
      });
    }
    return Container(
      child: Row(
        children: [
          Expanded(
              flex: 3,
              child: ListView.builder(
                itemCount: _list.length,
                itemBuilder: (context, index) {
                  return SizedBox(
                    width: MediaQuery.of(context).size.width,
                    child: Row(
                      children: [
                        Expanded(
                          child: SizedBox(
                            child: ListTile(
                              leading: _list[index].isFile
                                  ? const Icon(Icons.file_present)
                                  : const Icon(Icons.file_present_rounded),
                              title: Text(
                                _list[index].path,
                                style: const TextStyle(fontSize: 12),
                              ),
                              subtitle: Text(
                                  "${_list[index].permission}  ${_list[index].user}  ${_list[index].createDate}"),
                              onTap: () {
                                String path = _list[index].path;
                                setState(() {
                                  if(!_mounted){
                                    return;
                                  }
                                  _listRight.clear();
                                  _listRight.add(PhoneFile("返回", "", "", "", "", false, "","/", false));
                                });
                                CmdUtils.runCommand("adb -s ${ConnectUtils.getInstance().getCurrentChooseDevices()?.name} shell ls -a -l -F ${path}",
                                        (success, error, process, successListener) {
                                      if (success != "DONE" &&
                                          !success.startsWith("total ")) {
                                        List<String> array = success.split("\r\n");
                                        String tmp = "";
                                        for (String item in array) {
                                          List<String> contentArray =
                                          item.trim().split(RegExp('\\s+'));
                                          if (contentArray.isEmpty) {
                                            continue;
                                          }
                                          if (contentArray.length < 8) {
                                            tmp = tmp + item;
                                            contentArray = tmp.trim().split(RegExp('\\s+'));
                                            if (contentArray.length < 8) {
                                              continue;
                                            }
                                          }
                                          debugPrint("文件：${contentArray.length},${contentArray}");
                                          // debugPrint("长度为：${contentArray.length},内容：${contentArray}");
                                          if (contentArray.length == 8) {
                                            tmp = "";
                                            setState(() {
                                              if(!_mounted){
                                                return;
                                              }
                                              if (contentArray[7].endsWith("/") ||
                                                  contentArray[7].endsWith("@") ||
                                                  contentArray[7].endsWith("*")) {
                                                _listRight.add(PhoneFile(
                                                    contentArray[7].substring(0,
                                                        contentArray[7].length - 1),
                                                    contentArray[0],
                                                    contentArray[2],
                                                    contentArray[3],
                                                    "${contentArray[5]} ${contentArray[6]}",
                                                    false,"","${path}/${contentArray[7].substring(0,
                                                    contentArray[7].length - 1)}",
                                                    contentArray[0]
                                                        .startsWith("-")));
                                              } else {
                                                _listRight.add(PhoneFile(
                                                    contentArray[7],
                                                    contentArray[0],
                                                    contentArray[2],
                                                    contentArray[3],
                                                    "${contentArray[5]} ${contentArray[6]}",
                                                    false,"","${path}/${contentArray[7]}",
                                                    contentArray[0]
                                                        .startsWith("-")));
                                              }
                                            });
                                          } else if (contentArray.length == 10) {
                                            tmp = "";
                                            setState(() {
                                              if(!_mounted){
                                                return;
                                              }
                                              if (contentArray[7].endsWith("/") ||
                                                  contentArray[7].endsWith("@") ||
                                                  contentArray[7].endsWith("*")) {
                                                _listRight.add(PhoneFile(
                                                    contentArray[7].substring(0,
                                                        contentArray[7].length - 1),
                                                    contentArray[0],
                                                    contentArray[2],
                                                    contentArray[3],
                                                    "${contentArray[5]} ${contentArray[6]}",
                                                    true,contentArray[9],"${path}/${contentArray[7].substring(0,
                                                    contentArray[7].length - 1)}",
                                                    contentArray[0]
                                                        .startsWith("-")));
                                              } else {
                                                _listRight.add(PhoneFile(
                                                    contentArray[7],
                                                    contentArray[0],
                                                    contentArray[2],
                                                    contentArray[3],
                                                    "${contentArray[5]} ${contentArray[6]}",
                                                    true,contentArray[9],"${path}/${contentArray[7]}",
                                                    contentArray[0]
                                                        .startsWith("-")));
                                              }
                                            });
                                          }
                                        }
                                      }
                                    });
                              },
                              onLongPress: () {},
                            ),
                          ),
                        )
                      ],
                    ),
                  );
                },
              )),
          Container(
            color: Colors.black,
            width: 0.3,
          ),
          Expanded(
              flex: 7,
              child: ListView.builder(
                itemCount: _listRight.length,
                itemBuilder: (context, index) {
                  return SizedBox(
                    width: MediaQuery.of(context).size.width,
                    child: Row(
                      children: [
                        Expanded(
                          child: SizedBox(
                            child: ListTile(
                              leading: _listRight[index].isFile
                                  ? const Icon(Icons.file_present)
                                  : const Icon(Icons.file_present_rounded),
                              title: Text(
                                _listRight[index].path,
                                style: const TextStyle(fontSize: 12),
                              ),
                              subtitle: Text(
                                  "${_listRight[index].permission}  ${_listRight[index].user}  ${_listRight[index].createDate}"),
                              onTap: () {
                                String path = _listRight[index].realPath;
                                setState(() {
                                  if(!_mounted){
                                    return;
                                  }
                                  _listRight.clear();
                                  if(path.contains("/")){
                                    _listRight.add(PhoneFile("返回", "", "", "", "", false, "", path.substring(0,path.lastIndexOf("/")), false));
                                  }
                                });
                                CmdUtils.runCommand("adb -s ${ConnectUtils.getInstance().getCurrentChooseDevices()?.name} shell ls -a -l -F ${path}",
                                    (success, error, process, successListener) {
                                  debugPrint("目录内容：${success}");
                                  if (success != "DONE" &&
                                      !success.startsWith("total ")) {
                                    List<String> array = success.split("\r\n");
                                    String tmp = "";
                                    for (String item in array) {
                                      List<String> contentArray =
                                          item.trim().split(RegExp('\\s+'));
                                      if (contentArray.isEmpty) {
                                        continue;
                                      }
                                      if (contentArray.length < 8) {
                                        tmp = tmp + item;
                                        contentArray =
                                            item.trim().split(RegExp('\\s+'));
                                        if (contentArray.length < 8) {
                                          continue;
                                        }
                                      }
                                      // debugPrint("长度为：${contentArray.length},内容：${contentArray}");
                                      if (contentArray.length == 8) {
                                        tmp = "";
                                        setState(() {
                                          if(!_mounted){
                                            return;
                                          }
                                          if (contentArray[7].endsWith("/") ||
                                              contentArray[7].endsWith("@") ||
                                              contentArray[7].endsWith("*")) {
                                            _listRight.add(PhoneFile(
                                                contentArray[7].substring(0,
                                                    contentArray[7].length - 1),
                                                contentArray[0],
                                                contentArray[2],
                                                contentArray[3],
                                                "${contentArray[5]} ${contentArray[6]}",
                                                false,"","${path}/${contentArray[7].substring(0,
                                                contentArray[7].length - 1)}",
                                                contentArray[0]
                                                    .startsWith("-")));
                                          } else {
                                            _listRight.add(PhoneFile(
                                                contentArray[7],
                                                contentArray[0],
                                                contentArray[2],
                                                contentArray[3],
                                                "${contentArray[5]} ${contentArray[6]}",
                                                false,"","${path}/${contentArray[7]}",
                                                contentArray[0]
                                                    .startsWith("-")));
                                          }
                                        });
                                      } else if (contentArray.length == 10) {
                                        tmp = "";
                                        setState(() {
                                          if(!_mounted){
                                            return;
                                          }
                                          if (contentArray[7].endsWith("/") ||
                                              contentArray[7].endsWith("@") ||
                                              contentArray[7].endsWith("*")) {
                                            _listRight.add(PhoneFile(
                                                contentArray[7].substring(0,
                                                    contentArray[7].length - 1),
                                                contentArray[0],
                                                contentArray[2],
                                                contentArray[3],
                                                "${contentArray[5]} ${contentArray[6]}",
                                                true,contentArray[9],"${path}/${contentArray[7].substring(0,
                                                contentArray[7].length - 1)}",
                                                contentArray[0]
                                                    .startsWith("-")));
                                          } else {
                                            _listRight.add(PhoneFile(
                                                contentArray[7],
                                                contentArray[0],
                                                contentArray[2],
                                                contentArray[3],
                                                "${contentArray[5]} ${contentArray[6]}",
                                                true,contentArray[9],"${path}/${contentArray[7]}",
                                                contentArray[0]
                                                    .startsWith("-")));
                                          }
                                        });
                                      }
                                    }
                                  }
                                });
                              },
                              onLongPress: () {},
                            ),
                          ),
                        )
                      ],
                    ),
                  );
                },
              ))
        ],
      ),
    );
  }

  void initList() {
    CmdUtils.runCommand("adb -s ${ConnectUtils.getInstance().getCurrentChooseDevices()?.name} shell ls -a -l -F",
            (success, error, process, successListener) {
          if (success != "DONE" && !success.startsWith("total ")) {
            List<String> array = success.split("\r\n");
            String tmp = "";
            for (String item in array) {
              List<String> contentArray = item.trim().split(RegExp('\\s+'));
              debugPrint("文件：${contentArray.length},${contentArray}");
              if (contentArray.isEmpty) {
                continue;
              }
              if (contentArray.length < 8) {
                tmp = "$tmp $item";
                contentArray = tmp.trim().split(RegExp('\\s+'));
                if (contentArray.length < 8) {
                  continue;
                }
              }
              // debugPrint("长度为：${contentArray.length},内容：${contentArray}");
              if (contentArray.length == 8) {
                tmp = "";
                setState(() {
                  if(!_mounted){
                    return;
                  }
                  if (contentArray[7].endsWith("/") ||
                      contentArray[7].endsWith("@") ||
                      contentArray[7].endsWith("*")) {
                    _list.add(PhoneFile(
                        contentArray[7].substring(0, contentArray[7].length - 1),
                        contentArray[0],
                        contentArray[2],
                        contentArray[3],
                        "${contentArray[5]} ${contentArray[6]}",
                        false,"",contentArray[7].substring(0, contentArray[7].length - 1),
                        contentArray[0].startsWith("-")));
                  } else {
                    _list.add(PhoneFile(
                        contentArray[7],
                        contentArray[0],
                        contentArray[2],
                        contentArray[3],
                        "${contentArray[5]} ${contentArray[6]}",
                        false,"",contentArray[7],
                        contentArray[0].startsWith("-")));
                  }
                });
              } else if (contentArray.length == 10) {
                tmp = "";
                setState(() {
                  if(!_mounted){
                    return;
                  }
                  if (contentArray[7].endsWith("/") ||
                      contentArray[7].endsWith("@") ||
                      contentArray[7].endsWith("*")) {
                    _list.add(PhoneFile(
                        contentArray[7].substring(0, contentArray[7].length - 1 ),
                        contentArray[0],
                        contentArray[2],
                        contentArray[3],
                        "${contentArray[5]} ${contentArray[6]}",
                        true,contentArray[9],contentArray[7].substring(0, contentArray[7].length - 1),
                        contentArray[0].startsWith("-")));
                  } else {
                    _list.add(PhoneFile(
                        contentArray[7],
                        contentArray[0],
                        contentArray[2],
                        contentArray[3],
                        "${contentArray[5]} ${contentArray[6]}",
                        true,contentArray[9], contentArray[7],
                        contentArray[0].startsWith("-")));
                  }
                });
              }
            }
            setState(() {
              if(!_mounted){
                return;
              }
              _listRight.addAll(_list);
            });
          }
        });
  }
}
